package com.linshengjian.snowball.guard.service;

import com.linshengjian.snowball.guard.GuardProperties;
import com.linshengjian.snowball.guard.exception.ThirdPartyLoginException;
import com.linshengjian.snowball.guard.exception.UnknownLoginLabelException;
import com.linshengjian.snowball.guard.model.AuthUser;
import com.linshengjian.snowball.utils.SpringContextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Component
public class GuardUserService {

    @Autowired
    private GuardProperties properties;

    @Autowired
    private HttpServletRequest request;

    private String getLabel() {
        String label = request.getHeader(properties.getLogin().getHeader().getLabel());
        return label;
    }

    private ILoginLabelHandler getHandler() throws InstantiationException, IllegalAccessException {

        String label = getLabel();

        if (StringUtils.isEmpty(label))
            throw new UnknownLoginLabelException("没用指定登录标签");

        Class<? extends ILoginLabelHandler> handlerClass = properties.getLogin().getType().get(label);
        if (handlerClass == null)
            throw new UnknownLoginLabelException("未知的登录标签");
        return SpringContextUtils.getInstance(handlerClass);
    }

    /**
     * 获取用户
     * @param username
     * @return
     */
    public AuthUser findByUserName(String username) {
        try {
            AuthUser user = getHandler().findByUserName(username);
            user.setLoginLabel(getLabel());
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取用户
     * @param verifyObj 验证对象
     * @return
     */
    public AuthUser findByVerifyObj(String verifyObj){
        try {
            AuthUser user = getHandler().findByVerifyObj(verifyObj);
            user.setLoginLabel(getLabel());
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public AuthUser findByThirdParty(HttpServletRequest request) throws AuthenticationException {
        try {
            AuthUser user = getHandler().findByThirdParty(request);
            user.setLoginLabel(getLabel());
            return user;
        } catch (Exception e) {
            if (e instanceof AuthenticationException)
                throw (AuthenticationException) e;
            throw new ThirdPartyLoginException(e.getMessage(), e.getCause());
        }
    }
}
